//
//  ANWebService+Product.m
//  Ants
//
//  Created by ZHM on 16/7/4.
//  Copyright © 2016年 ZHM. All rights reserved.
//

#import "ANWebService+Product.h"
#import <CoreLocation/CoreLocation.h>
@implementation ANWebService (Product)


/**
 * 初始化类
 */
- (void)fetchProductCategoryCompletion:(void(^)(NSArray *productCategorys, NSError *error))completion {
    BmobQuery *bquery = [BmobQuery queryWithClassName:@"ProductCategory"];
    [bquery orderByAscending:@"title"];
    [bquery findObjectsInBackgroundWithBlock:^(NSArray *array, NSError *error) {
        if (!error) {
            ANLog(@"网络获取类:%ld",(unsigned long)array.count);
            NSMutableArray *productCategorys = [NSMutableArray new];
            [array enumerateObjectsUsingBlock:^(BmobObject *obj, NSUInteger idx, BOOL * _Nonnull stop) {
                [productCategorys addObject:[self productCategoryFormBmobObject:obj]];
            }];
            self.categorys = productCategorys;
            ANLog(@"_productCategorys:%ld--%ld",self.categorys.count,productCategorys.count);
            BLOCK_SAFE_ASY_RUN_MainQueue(completion, productCategorys, nil);
        }else {
            BLOCK_SAFE_ASY_RUN_MainQueue(completion, nil, error);
        }
    }];
}
- (void)fetchProductQuantity:(ANBDProduct *)product completion:(void(^)(NSInteger quantity, NSError *error))completion {
    BmobQuery   *bquery = [BmobQuery queryWithClassName:@"Product"];
    [bquery getObjectInBackgroundWithId:product.mlObjectId block:^(BmobObject *object, NSError *error) {
        if (!error) {
            NSInteger quantity = [[object objectForKey:@"quantity"] integerValue];
            BLOCK_SAFE_ASY_RUN_MainQueue(completion, quantity, nil);
        } else {
            BLOCK_SAFE_ASY_RUN_MainQueue(completion, 0, error);
        }
    }];
}

- (void)updateProduct:(ANBDProduct *)product Category:(ANBDProductCategory *)category beforeCategory:(ANBDProductCategory *)beforeCategory completion:(void(^)(BOOL succeeded, NSError *error))completion {
    BmobQuery   *bquery = [BmobQuery queryWithClassName:@"Product"];
    [bquery getObjectInBackgroundWithId:product.mlObjectId block:^(BmobObject *object, NSError *error) {
        if (!error) {
            object = [self bmobObject:object FormProduct:product];
            [object setObject:category.bmObject forKey:@"category"];
            [object updateInBackgroundWithResultBlock:^(BOOL isSuccessful, NSError *error) {
                if (!error) {
                    if ([category.title isEqualToString:beforeCategory.title]) {
                        ANLog(@"修改成功");
                        BLOCK_SAFE_ASY_RUN_MainQueue(completion, YES, nil);
                        [SVProgressHUD showSuccessWithStatus:@"修改成功!"];
                        return ;
                    }
                    //删除一个关联
                    BmobRelation *relationRemove = [[BmobRelation alloc] init];
                    [relationRemove removeObject:object];
                    BmobObject *beforeCategoryObject = (BmobObject *)beforeCategory.bmObject;
                    [beforeCategoryObject addRelation:relationRemove forKey:@"product"];
                    [beforeCategoryObject updateInBackgroundWithResultBlock:^(BOOL isSuccessful, NSError *error) {
                        if (!error) {
                            ANLog(@"解除关联成功");
                            BLOCK_SAFE_ASY_RUN_MainQueue(completion, YES, nil);
                            [SVProgressHUD showSuccessWithStatus:@"解除关联成功!"];
                        }
                    }];
                    BmobRelation *relation = [[BmobRelation alloc] init];
                    [relation addObject:object];
                    BmobObject *categoryObject = (BmobObject *)category.bmObject;
                    [categoryObject addRelation:relation forKey:@"product"];
                    [categoryObject updateInBackgroundWithResultBlock:^(BOOL isSuccessful, NSError *error) {
                        if (!error) {
                            ANLog(@"修改成功");
                            BLOCK_SAFE_ASY_RUN_MainQueue(completion, YES, nil);
                            [SVProgressHUD showSuccessWithStatus:@"修改成功!"];
                        }
                    }];
                } else {
                    ANLog(@"出错:%@",error);
                    [SVProgressHUD showSuccessWithStatus:@"修改失败!"];
                    BLOCK_SAFE_ASY_RUN_MainQueue(completion, NO, error);
                }
            }];
        }
    }];
}
- (void)releaseNewProduct:(ANBDProduct *)product Category:(ANBDProductCategory *)category completion:(void(^)(BOOL succeeded, NSError *error))completion {
    BmobObject  *object = [BmobObject objectWithClassName:@"Product"];
    object = [self bmobObject:object FormProduct:product];
    [object setObject:[self currentUser] forKey:@"user"];
    [object setObject:category.bmObject forKey:@"category"];
    [object saveInBackgroundWithResultBlock:^(BOOL isSuccessful, NSError *error) {
        if (!error) {
            BmobRelation *relation = [[BmobRelation alloc] init];
            [relation addObject:object];
            BmobObject *categoryObject = (BmobObject *)category.bmObject;
            [categoryObject addRelation:relation forKey:@"product"];
            [categoryObject updateInBackgroundWithResultBlock:^(BOOL isSuccessful, NSError *error) {
                if (!error) {
                    ANLog(@"发布成功");
                    BLOCK_SAFE_ASY_RUN_MainQueue(completion, YES, nil);
                    [SVProgressHUD showSuccessWithStatus:@"发布成功!"];
                }
            }];
        } else {
            ANLog(@"出错:%@",error);
            [SVProgressHUD showSuccessWithStatus:@"发布失败!"];
            BLOCK_SAFE_ASY_RUN_MainQueue(completion, NO, error);
        }
    }];
}
/**
 * 批量上传图片
 */
- (void)uploadPhotos:(NSArray *)images completion:(void(^)(NSArray *filePaths, BOOL succeeded, NSError *error))completion {
    if (images.count == 0) {
        return;
    }
    NSMutableArray *arrayM = [NSMutableArray array];
    //NSMutableArray *arrayMin = [NSMutableArray array];
    for (int i = 0;i < images.count;i++) {
        UIImage *image = images[i];
        NSData *imageData = UIImageJPEGRepresentation(image, 1.0);
        NSData *imageDataMin;
        ANLog(@"%ld",(unsigned long)imageData.length);
        //显示图片大小 512KB以下
        if ([imageData length] > 262144) {
            imageData = UIImageJPEGRepresentation(image, 262144.0f/[imageData length]);
        }
        
        
        ANLog(@">>>> %ld",(unsigned long)imageData.length);
        UIImage *imageMin = [UIImage imageWithData:imageData];
        if (imageMin.size.width > 320) {
            ANLog(@"320比例: == %f",320.0/imageMin.size.width);
            imageMin = [imageMin imageCompressWithSimple:imageMin scale:320.0/imageMin.size.width];
        }else if (imageMin.size.height > 180) {
            ANLog(@"180比例: == %f",180.0/imageMin.size.height);
            imageMin = [imageMin imageCompressWithSimple:imageMin scale:180.0/imageMin.size.height];
            
        }
        NSData *data = UIImageJPEGRepresentation(imageMin, 1.0);
        ANLog(@"缩小比例: == %f",24576.0/data.length);
        imageDataMin = UIImageJPEGRepresentation(imageMin, 24576.0/data.length);
        
        
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"yyyyMMddHHmmss"];
        NSString *imageName = [NSString stringWithFormat:@"pic%@%d.jpg",[dateFormatter stringFromDate:[NSDate date]],i];
        NSDictionary *imageDic = @{@"filename":imageName,@"data":imageData};
        NSDictionary *imageDicMin = @{@"filename":[NSString stringWithFormat:@"min%@",imageName],@"data":imageDataMin};
        
        [arrayM addObject:imageDicMin];
        [arrayM addObject:imageDic];
    }
    
    [BmobFile filesUploadBatchWithDataArray:arrayM progressBlock:^(int index, float progress) {
        //进程合并显示
        [SVProgressHUD showProgress:progress/arrayM.count + 1.0/arrayM.count*index status:@"上传数据..."];
    } resultBlock:^(NSArray *array, BOOL isSuccessful, NSError *error) {
        if (!error) {
            ANLog(@"%@",array);
            NSMutableArray *arrayPath = [NSMutableArray array];
            int i = 0;
            while (i < array.count) {
                BmobFile *minPic = array[i];
                BmobFile *maxPic = array[i + 1];
                NSDictionary *dic = @{@"minPic":minPic.url,@"maxPic":maxPic.url};
                [arrayPath addObject:dic];
                i = i + 2;
            }
            
            ANLog(@"过滤后上传的图片个数:%ld",arrayPath.count);
            [SVProgressHUD dismiss];
            BLOCK_SAFE_ASY_RUN_MainQueue(completion,arrayPath,YES,nil);
        } else {
            BLOCK_SAFE_ASY_RUN_MainQueue(completion,nil,NO,error);
        }
    }];
}

/**
 * 删除商品
 */
- (void)removeProduct:(ANBDProduct *)product isRemoveWeb:(BOOL)isRemoveWeb  completion:(void(^)(BOOL succeeded, NSError *error))completion {
    if (!product) {
        return;
    }
    if (isRemoveWeb) {
        BmobObject *bmobObject = [BmobObject objectWithoutDataWithClassName:@"Product"  objectId:product.mlObjectId];
        NSMutableArray *prepareMaxDelete = [NSMutableArray array];
        NSMutableArray *prepareMinDelete = [NSMutableArray array];
        for (NSDictionary *dic in product.icons) {
            [prepareMaxDelete addObject:dic[@"maxPic"]];
            [prepareMinDelete addObject:dic[@"minPic"]];
        }
        [self removeFilesWithArray:prepareMaxDelete  completion:^(NSArray *filePaths, BOOL succeeded, NSError *error) {
            if (!error) {
                ANLog(@"图片删除");
            }else {
                ANLog(@"图片删除失败:%@",error);
            }
        }];
        [self removeFilesWithArray:prepareMinDelete  completion:^(NSArray *filePaths, BOOL succeeded, NSError *error) {
            if (!error) {
                ANLog(@"图片删除");
            }else {
                ANLog(@"图片删除失败:%@",error);
            }
        }];
        [bmobObject deleteInBackgroundWithBlock:^(BOOL isSuccessful, NSError *error) {
            if (!error) {
                ANLog(@" mlObjectId---%@",product.mlObjectId);
                //发送通知
                [[NSNotificationCenter defaultCenter] postNotificationName:@"RemoveProductCompletion" object:product.mlObjectId];
                ANBDProduct *productDelete = [ANBDProduct MR_findFirstByAttribute:@"mlObjectId" withValue:product.mlObjectId inContext:self.sharedContext];
                [productDelete MR_deleteEntityInContext:self.sharedContext];
                [self.sharedContext MR_saveToPersistentStoreAndWait];
                BLOCK_SAFE_ASY_RUN_MainQueue(completion,YES,nil);
                [SVProgressHUD showSuccessWithStatus:@"删除成功!"];
            }else {
                [SVProgressHUD showSuccessWithStatus:@"删除失败!"];
                BLOCK_SAFE_ASY_RUN_MainQueue(completion,NO,error);
            }
        }];
    }else {
        //发送通知
        [[NSNotificationCenter defaultCenter] postNotificationName:@"RemoveProductCompletion" object:product.mlObjectId];
        ANBDProduct *productDelete = [ANBDProduct MR_findFirstByAttribute:@"mlObjectId" withValue:product.mlObjectId inContext:self.sharedContext];
        [productDelete MR_deleteEntityInContext:self.sharedContext];
        [self.sharedContext MR_saveToPersistentStoreAndWait];
    }
}

/**
 * 批量删除文件 - urls (NSString)
 */
- (void)removeFilesWithArray:(NSArray *)urls completion:(void(^)(NSArray *filePaths, BOOL succeeded, NSError *error))completion {
    if (urls.count == 0) {
        return;
    }
    [BmobFile filesDeleteBatchWithArray:urls resultBlock:^(NSArray *array, BOOL isSuccessful, NSError *error) {
        if (!error) {
            for (NSString *url in urls) {
                //删除缓存图片
                [[SDImageCache sharedImageCache] removeImageForKey:url];
            }
            BLOCK_SAFE_ASY_RUN_MainQueue(completion,array,YES,nil);
        }else {
            BLOCK_SAFE_ASY_RUN_MainQueue(completion,nil,NO,error);
        }
    }];
}
- (void)fetchProductsFromParam:(ANProductGetParam*)param completion:(void(^)(NSArray *products, BOOL isReachEnd, NSError *error))completion {
    BmobQuery *query = [BmobQuery queryWithClassName:@"Product"];
    query.limit = perPage;
    BOOL ByAscending = YES;
    
    if (param.isCurrentUser) {
        ANBmobUser *user = [self currentUser];
        NSDictionary *condiction = @{@"user":@{@"__type":@"Pointer",@"className":@"_User",@"objectId":user.objectId}};
        [query addTheConstraintByOrOperationWithArray:@[condiction]];
    }
    
    //按时间获取
    if (param.isDateSort) {
        if (param.isLoadNew) {
            ByAscending = !param.isAscending;
            if (param.newsDate) {
                //加1秒
                param.newsDate = [NSDate dateWithTimeInterval:1 sinceDate:param.newsDate];
                [query whereKey:@"createdAt" greaterThan:param.newsDate];
            }
        } else {
            ByAscending = param.isAscending;
            if (param.moreDate) {
                [query whereKey:@"createdAt" lessThan:param.moreDate];
            }
        }
    }
    //距离查询
    if (param.isLocationSort) {
        CLLocation *location = (CLLocation *)param.sortmoreValue;
        BmobGeoPoint *geoPoint = [[BmobGeoPoint alloc] initWithLongitude:location.coordinate.longitude WithLatitude:location.coordinate.latitude];
        if (!param.isLoadNew) {
            ByAscending = param.isAscending;
            [query whereKey:param.sortKey nearGeoPoint:geoPoint withinKilometers:10000];
            query.skip = param.skipMore;
        }else {
            BLOCK_SAFE_ASY_RUN_MainQueue(completion, nil, YES, nil);
            return;
        }
    }
    //价格查询
    if (param.isPriceSort) {
        if (param.isLoadNew) {
            BLOCK_SAFE_ASY_RUN_MainQueue(completion, nil, YES, nil);
            return;
        } else {
            ByAscending = param.isAscending;
            ANLog(@"跳过:%ld",(long)param.skipMore);
            query.skip = param.skipMore;
        }
    }
    //区域
    if (param.address) {
        [query whereKey:@"address" containsAll:param.address];
    }
    
    //关联- 分类
    if (param.relationKey) {
        [query whereObjectKey:param.relationKey relatedTo:param.relationObj];
    }
    //根据KEY -- 排序
    if (!param.isLocationSort) {
        if (ByAscending) {
            [query orderByAscending:param.sortKey];
        } else {
            [query orderByDescending:param.sortKey];
        }
    }
    
    //关联对象信息一并查询出来]
    [query includeKey:@"category"];
    [query findObjectsInBackgroundWithBlock:^(NSArray *array, NSError *error) {
        if (!error) {
            NSMutableArray *arrayM = [NSMutableArray array];
            [array enumerateObjectsUsingBlock:^(BmobObject *obj, NSUInteger idx, BOOL * _Nonnull stop) {
                ANBDProduct *product = [self productFormBmobObject:obj];
                [arrayM addObject:product];
            }];
            BLOCK_SAFE_ASY_RUN_MainQueue(completion, arrayM, arrayM.count < perPage, nil);
        }else {
            BLOCK_SAFE_ASY_RUN_MainQueue(completion, nil, NO, error);
        }
    }];
}
//- (void)fetchCurrentUserProductsFromPage:(NSUInteger)page completion:(void(^)(NSArray *products, BOOL isReachEnd, NSError *error))completion {
//    BmobQuery *query = [BmobQuery queryWithClassName:@"Product"];
//    //关联对象信息一并查询出来
//    [query includeKey:@"category"];
//    query.skip = page * perPage;
//    query.limit = perPage;
//    ANBmobUser *user = [self currentUser];
//    NSDictionary *condiction = @{@"user":@{@"__type":@"Pointer",@"className":@"_User",@"objectId":user.objectId}};
//    [query addTheConstraintByOrOperationWithArray:@[condiction]];
//    [query findObjectsInBackgroundWithBlock:^(NSArray *array, NSError *error) {
//        if (!error) {
//            NSMutableArray *arrayM = [NSMutableArray array];
//            [array enumerateObjectsUsingBlock:^(BmobObject *obj, NSUInteger idx, BOOL * _Nonnull stop) {
//                ANBDProduct *product = [self productFormBmobObject:obj];
//                [arrayM addObject:product];
//            }];
//            BLOCK_SAFE_ASY_RUN_MainQueue(completion, arrayM, arrayM.count < perPage, nil);
//        }else {
//            BLOCK_SAFE_ASY_RUN_MainQueue(completion, nil, NO, error);
//        }
//    }];
//}



@end
